<template>
  <div class="admin--page-content">
    <div class="admin--form">
      <table class="admin--form--table">
        <colgroup>
          <col style="width: 140px;">
          <col>
        </colgroup>
        <tbody>
          <tr>
            <th><div>분야</div></th>
            <td>{{ data.field_name || "-" }}</td>
          </tr>
          <tr>
            <th><div>지역</div></th>
            <td>{{ data.area_name || "-" }}</td>
          </tr>
          <tr>
            <th><div>선상명</div></th>
            <td class="admin--table-title">{{ data.name || "-" }}</td>
          </tr>
          <tr>
            <th><div>낚시지역</div></th>
            <td>{{ data.area_detail || "-" }}</td>
          </tr>
          <tr>
            <th><div>중량(톤수)</div></th>
            <td>{{ data.tonnage || "-" }}</td>
          </tr>
          <tr>
            <th><div>탑승인원</div></th>
            <td>{{ data.capacity || "-" }}</td>
          </tr>
          <tr>
            <th><div>우편번호</div></th>
            <td>{{ data.zip_code || "-" }}</td>
          </tr>
          <tr>
            <th><div>주소</div></th>
            <td>{{ data.address || "-" }}</td>
          </tr>
          <tr>
            <th><div>상세주소</div></th>
            <td>{{ data.address_detail || "-" }}</td>
          </tr>
          <tr>
            <th><div>참고항목</div></th>
            <td>{{ data.address_refer || "-" }}</td>
          </tr>
          <tr>
            <th><div>좌표</div></th>
            <td>
              <template v-if="data.lat && data.lng">{{ data.lat }}, {{ data.lng }}</template>
              <template v-else>-</template>
            </td>
          </tr>
          <tr>
            <th><div>사진</div></th>
            <td>
              <div v-if="data.photos && data.photos.length" class="onboard--photo-grid">
                <div v-for="p in data.photos" :key="p.id" class="onboard--photo-item">
                  <img :src="getImageUrl(p.file_path)" :alt="p.original_name" />
                </div>
              </div>
              <template v-else>-</template>
            </td>
          </tr>
          <tr>
            <th><div>제휴 여부</div></th>
            <td>
              <span :class="['admin--badge', data.partnership_YN === 'Y' ? 'admin--badge-active' : 'admin--badge-ended']">
                {{ data.partnership_YN === "Y" ? "제휴" : "비제휴" }}
              </span>
            </td>
          </tr>
          <tr v-if="data.partnership_YN === 'Y'">
            <th><div>계좌번호</div></th>
            <td>
              <template v-if="data.account_number">
                {{ bankName(data.bank_code) }} {{ data.account_number }}<template v-if="data.account_holder"> ({{ data.account_holder }})</template>
              </template>
              <template v-else>-</template>
            </td>
          </tr>
          <tr>
            <th><div>상태</div></th>
            <td>
              <span :class="['admin--badge', data.status_YN === 'Y' ? 'admin--badge-active' : 'admin--badge-ended']">
                {{ data.status_YN === "Y" ? "사용중" : "미사용" }}
              </span>
            </td>
          </tr>
          <tr>
            <th><div>등록일</div></th>
            <td>{{ formatDateTime(data.created_at) }}</td>
          </tr>
          <tr>
            <th><div>최근 수정</div></th>
            <td>{{ formatDateTime(data.updated_at) }}</td>
          </tr>
        </tbody>
      </table>

      <!-- 버튼 영역 -->
      <div class="admin--form-actions">
        <button type="button" class="admin--btn" @click="goToList">
          ← 목록으로
        </button>
        <button type="button" class="admin--btn admin--btn-red-border ml--auto" @click="handleDelete">
          삭제
        </button>
        <button type="button" class="admin--btn admin--btn-red" @click="goToEdit">
          수정
        </button>
      </div>

      <!-- 알림 모달 -->
      <AdminAlertModal
        v-if="alertModal.show"
        :title="alertModal.title"
        :message="alertModal.message"
        :type="alertModal.type"
        @confirm="handleAlertConfirm"
        @cancel="handleAlertCancel"
        @close="closeAlertModal"
      />
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted } from "vue";
  import { useRoute, useRouter } from "vue-router";
  import AdminAlertModal from "~/components/admin/AdminAlertModal.vue";

  definePageMeta({
    layout: "admin",
    middleware: ["auth"],
  });

  const route = useRoute();
  const router = useRouter();
  const { get, del } = useApi();
  const { getImageUrl } = useImage();

  const onboardId = route.params.id;

  const data = ref({
    field_name: "",
    area_name: "",
    name: "",
    area_detail: "",
    tonnage: "",
    capacity: "",
    zip_code: "",
    address: "",
    address_detail: "",
    address_refer: "",
    lat: "",
    lng: "",
    bank_code: "",
    account_number: "",
    account_holder: "",
    partnership_YN: "N",
    status_YN: "Y",
    created_at: "",
    updated_at: "",
    photos: [],
  });

  // 은행 코드 → 은행명
  const bankMap = {
    "002": "산업은행", "003": "기업은행", "004": "국민은행", "007": "수협은행",
    "011": "농협은행", "020": "우리은행", "023": "SC제일은행", "031": "대구은행",
    "032": "부산은행", "034": "광주은행", "035": "제주은행", "037": "전북은행",
    "039": "경남은행", "045": "새마을금고", "071": "우체국", "081": "하나은행",
    "088": "신한은행", "089": "케이뱅크", "090": "카카오뱅크", "092": "토스뱅크",
  };
  const bankName = (code) => bankMap[code] || (code ? code : "-");

  // 알림 모달
  const alertModal = ref({
    show: false,
    title: "알림",
    message: "",
    type: "alert",
    onConfirm: null,
  });

  const showAlert = (message, title = "알림") => {
    alertModal.value = { show: true, title, message, type: "alert", onConfirm: null };
  };
  const showConfirm = (message, onConfirm, title = "확인") => {
    alertModal.value = { show: true, title, message, type: "confirm", onConfirm };
  };
  const closeAlertModal = () => { alertModal.value.show = false; };
  const handleAlertConfirm = () => {
    if (alertModal.value.onConfirm) alertModal.value.onConfirm();
    closeAlertModal();
  };
  const handleAlertCancel = () => closeAlertModal();

  // 상세 조회
  const loadDetail = async () => {
    const { data: res, error } = await get(`/onboard/${onboardId}`);

    if (error || !res?.success) {
      showAlert(error?.message || res?.message || "조회에 실패했습니다.", "오류");
      return;
    }

    const row = res.data || {};
    data.value = {
      field_name: row.field_name ?? "",
      area_name: row.area_name ?? "",
      name: row.name ?? "",
      area_detail: row.area_detail ?? "",
      tonnage: row.tonnage ?? "",
      capacity: row.capacity ?? "",
      zip_code: row.zip_code ?? "",
      address: row.address ?? "",
      address_detail: row.address_detail ?? "",
      address_refer: row.address_refer ?? "",
      lat: row.lat ?? "",
      lng: row.lng ?? "",
      bank_code: row.bank_code ?? "",
      account_number: row.account_number ?? "",
      account_holder: row.account_holder ?? "",
      partnership_YN: row.partnership_YN ?? "N",
      status_YN: row.status_YN ?? "Y",
      created_at: row.created_at ?? "",
      updated_at: row.updated_at ?? "",
      photos: row.photos ?? [],
    };
  };

  // 삭제
  const handleDelete = () => {
    showConfirm(
      `'${data.value.name}' 선상을 삭제하시겠습니까?`,
      async () => {
        const { data: res, error } = await del(`/onboard/${onboardId}`);
        if (error || !res?.success) {
          showAlert(error?.message || res?.message || "삭제에 실패했습니다.", "오류");
        } else {
          showAlert(res.message || "삭제되었습니다.", "성공");
          setTimeout(() => router.push("/site-manager/onboard/list"), 800);
        }
      },
      "선상 삭제"
    );
  };

  // 이동
  const goToList = () => router.push("/site-manager/onboard/list");
  const goToEdit = () => router.push(`/site-manager/onboard/edit/${onboardId}`);

  // 일시 포맷
  const formatDateTime = (dateString) => {
    if (!dateString) return "-";
    const date = new Date(dateString.replace(" ", "T"));
    if (isNaN(date.getTime())) return dateString;
    return date.toLocaleString("ko-KR", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  onMounted(() => {
    loadDetail();
  });
</script>